package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.SubAreaService;
import cn.itcast.bos.web.action.base.web.utils.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import sun.misc.BASE64Encoder;


import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@Scope("prototype")
@ParentPackage(("json-default"))
@Namespace("/")
public class SubAreaAction extends BaseAction<SubArea> {

    @Autowired
    private SubAreaService subAreaService;

    @Action(value = "subarea_pageQuery",results = {@Result(name="success",type = "json")})
    public String pageQuery(){
        Pageable pageable =  new PageRequest(page-1,rows);
        Specification<SubArea> specification = new Specification<SubArea>() {
            List<Predicate> list = new ArrayList<Predicate>();
            @Override
            public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Join<SubArea, Area> areaRoot = root.join("area", JoinType.INNER);
                if(model.getArea()!=null&&StringUtils.isNotBlank(model.getArea().getProvince())){
                    Predicate province = cb.like(areaRoot.get("province").as(String.class), "%" + model.getArea().getProvince() + "%");
                    list.add(province);
                }
                if(model.getArea()!=null&&StringUtils.isNotBlank(model.getArea().getCity())){
                    Predicate city = cb.like(areaRoot.get("city").as(String.class), "%" + model.getArea().getCity() + "%");
                    list.add(city);
                }
                if(model.getArea()!=null&&StringUtils.isNotBlank(model.getArea().getDistrict())){
                    Predicate district = cb.like(areaRoot.get("district").as(String.class), "%" + model.getArea().getDistrict() + "%");
                    list.add(district);

                }
                Join<SubArea, FixedArea> fixedAreaJoin = root.join("fixedArea", JoinType.INNER);
                if (model.getFixedArea()!=null&&StringUtils.isNotBlank(model.getFixedArea().getId())){
                    Predicate id = cb.equal(fixedAreaJoin.get("id").as(Integer.class), model.getFixedArea().getId());
                    list.add(id);
                }
                if (StringUtils.isNotBlank(model.getAssistKeyWords())){
                    Predicate assistKeyWords = cb.equal(root.get("assistKeyWords").as(String.class), model.getAssistKeyWords());
                    list.add(assistKeyWords);
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
       Page<SubArea> pageData =  subAreaService.findAll(specification,pageable);
       PagePushIntoValueStack(pageData);

        return SUCCESS;
    }

    private File file;
    private String fileFileName;

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    @Action("subArea_upload")
    public String importSubArea() throws IOException {
        Workbook workbook = null;
        if(fileFileName.endsWith(".xls")){
            workbook = new HSSFWorkbook(new FileInputStream(file));
        }else if(fileFileName.endsWith(".xlsx")){
            workbook = new XSSFWorkbook(new FileInputStream(file));
        }
        List<SubArea> subAreas = new ArrayList<SubArea>();
        Sheet sheet = workbook.getSheet("Sheet1");

        for (Row row: sheet
             ) {
            if (row.getRowNum() == 0) {
                continue;
            }
            SubArea subArea = new SubArea();
            FixedArea fixedArea = new FixedArea();
            Area area = new Area();
            subArea.setId(row.getCell(0).getStringCellValue());
            fixedArea.setId(row.getCell(1).getStringCellValue());
            area.setId(row.getCell(2).getStringCellValue());
            subArea.setKeyWords(row.getCell(3).getStringCellValue());
            subArea.setStartNum(row.getCell(4).getStringCellValue());
            subArea.setEndNum(row.getCell(5).getStringCellValue());
            subArea.setSingle(row.getCell(6).getStringCellValue().charAt(0));
            subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());
            subArea.setFixedArea(fixedArea);
            subArea.setArea(area);
            subAreas.add(subArea);

        }
        subAreaService.save(subAreas);

        return NONE;
    }

    @Action(value = "subarea_save",results = {@Result(name = "success",type = "redirect",location = "./pages/base/sub_area.html")})
    public String save(){
        subAreaService.save(model);
        return SUCCESS;
    }

    @Action(value="subarea_export")
    public String export(){
        List<SubArea> list = subAreaService.findAll();
        XSSFWorkbook xssfSheets = new XSSFWorkbook();
        XSSFSheet sheet = xssfSheets.createSheet("子区");
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("分区编号");
        row.createCell(1).setCellValue("定区编码");
        row.createCell(2).setCellValue("区域编码");
        row.createCell(3).setCellValue("关键字");
        row.createCell(4).setCellValue("起始号");
        row.createCell(5).setCellValue("结束号");
        row.createCell(6).setCellValue("单双号");
        row.createCell(7).setCellValue("位置信息");
        for (int i = 0;i<list.size();i++){
           SubArea subArea = list.get(i);
            XSSFRow rowI = sheet.createRow(i+1);
            rowI.createCell(0).setCellValue(subArea.getId());
            rowI.createCell(1).setCellValue(subArea.getFixedArea().getId());
            rowI.createCell(2).setCellValue(subArea.getArea().getId());
            rowI.createCell(3).setCellValue(subArea.getKeyWords());
            rowI.createCell(4).setCellValue(subArea.getStartNum());
            rowI.createCell(5).setCellValue(subArea.getEndNum());
            rowI.createCell(6).setCellValue(subArea.getEndNum());
            rowI.createCell(7).setCellValue(subArea.getAssistKeyWords());
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        String file = "分区表格.xlsx";
        String header = ServletActionContext.getRequest().getHeader("User-Agent");
        try {
        if(header.contains("Firefox")){

                file="=?UTF-8?B?"
                    + new String(new BASE64Encoder().encode(file.getBytes("UTF-8"))) + "?=";

        }else {
            file =URLEncoder.encode(file,"UTF-8").replace("+"," ");

        }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType(ServletActionContext.getServletContext().getMimeType(file));
        response.setHeader("content-disposition","attachment;filename="+file);
        try {
            xssfSheets.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NONE;
    }
}
